<template>
    <uni-data-picker class="app-city-picker" v-slot:default="{ data, error, options }" :map="{ text: 'name', value: 'code' }"
        v-model="formData.code" ref="picker" :localdata="cities" popup-title="请选择地区" @change="onChange">
        <uv-input v-if="!loading" v-model="formData.displayText" disabled disabledColor="#ffffff" placeholder="请选择"
            border="none">
        </uv-input>
        <view v-else>{{ error || '加载中...' }}</view>
    </uni-data-picker>
</template>
<script setup lang="ts">
import { ref, onMounted, watch, defineEmits, defineProps } from 'vue'
import { convertToJson } from '@/utils/index';
import { cities as getCitySource } from '@/services/platform'
const cities = ref([])
const loading = ref(true)

const props = defineProps({
    modelValue: {
        type: String
    }
})

const emit = defineEmits(['update:modelValue','change'])

const formData = ref({
    code: '',
    regionData: [],
    displayText: ''
})

const getCities = () => {
    loading.value = true
    getCitySource().then(data => {
        cities.value = data
        initForm()
    }).catch((err) => { console.log(err) }).finally(() => { loading.value = false })
}

const initForm = () => {
    if (props.modelValue && props.modelValue.length > 1) {
        const array = convertToJson(props.modelValue, 'array')
        if (array.length) {
            formData.value.code = array[array.length - 1].code
        }
        formData.value.regionData = array
        formData.value.displayText = array.map(p => p.name).join(' ')
    } else {
        formData.value.code = ' '// 坑批组件, 只能这么写才能显示数据
        formData.value.displayText = null
    }
}

watch(() => props.modelValue, () => {
    initForm()
}, {
    immediate: true
})

onMounted(() => {
    getCities()
})

const onChange = ({ detail }) => {
    const array = detail.value.map(p => {
        return {
            code: p.value,
            name: p.text
        }
    })
    const json = JSON.stringify(array)
    formData.value.displayText = detail.value.map(p => p.text).join(' ')
    emit('update:modelValue', json)
    emit('change')
}
</script>
<style scoped>
.app-city-picker /deep/ .selected-area {
    flex: none;
    height: auto;
}
</style>